package com.zuofei.xmpp.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.zuofei.xmpp.R;
import com.zuofei.xmpp.dbhelper.SmsOpenHelper;
import com.zuofei.xmpp.provider.SmsProvider;
import com.zuofei.xmpp.service.IMService;
import com.zuofei.xmpp.utils.ThreadUtils;

import org.jivesoftware.smack.packet.Message;

import java.text.SimpleDateFormat;
import java.util.Date;

public class ChatActivity extends AppCompatActivity {

    public static final String CLICKACCOUNT = "clickaccount";
    public static final String CLICKNICKNAME = "clicknickname";
    private String clickAccount;
    private String clickNickName;

    TextView mTitle;
    ListView mListView;
    EditText mEtBody;
    Button mBtnSend;
    private CursorAdapter mAdapter;
    private IMService mImService;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        init();
        initView();
        initData();
        initListener();
    }

    private void initListener() {
        mBtnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String body = mEtBody.getText().toString();
                //发送消息
                sendMessage(clickAccount, body);
                //清空输入框
                clearInput();
            }
        });
    }

    private void clearInput() {
        mEtBody.setText("");
    }

    private void sendMessage(final String toUserId, final String content) {
        ThreadUtils.runInThread(new Runnable() {
            @Override
            public void run() {
                String body = mEtBody.getText().toString();
                //初始化消息
                Message message = new Message();
                message.setFrom(IMService.mCurAccount);
                message.setTo(clickAccount);
                message.setBody(body);
                message.setType(Message.Type.chat);
                message.setProperty("key", "value");
                //调用服务器里面的sendMessage方法
                mImService.sendMessage(message);

                ThreadUtils.runInThread(new Runnable() {
                    @Override
                    public void run() {
                        mEtBody.setText("");
                    }
                });
            }
        });
    }


    private void initData() {

        setAdapterOrNotify();
    }

    private void setAdapterOrNotify() {
        //1.首先判断是否存在adapter
        if (mAdapter != null) {
            Cursor cursor = mAdapter.getCursor();
            cursor.requery();
            mListView.setSelection(cursor.getCount() - 1);
            return;
        }
        ThreadUtils.runInThread(new Runnable() {
            @Override
            public void run() {
                //selection条件
                final Cursor cursor = getContentResolver().query(SmsProvider.URI_SMS, null,
                        "(from_account = ? and to_account = ?) or (from_account = ? and to_account = ?)",
                        new String[]{IMService.mCurAccount, clickAccount, clickAccount, IMService.mCurAccount}, SmsOpenHelper.SMSTable.TIME+" ASC");

//                final Cursor cursor = getContentResolver().query(SmsProvider.URI_SMS, null,
//                        "(from_account = ? and to_account = ?)",
//                        new String[]{clickAccount, IMService.mCurAccount}, SmsOpenHelper.SMSTable.TIME+" ASC");
                if (cursor.getCount() < 1) {
                    return;
                }
                ThreadUtils.runInUIThread(new Runnable() {
                    @Override
                    public void run() {
                        mAdapter = new CursorAdapter(ChatActivity.this, cursor) {
                            public static final int RECEIVE = 1;
                            public static final int SEND = 0;
//                            @Override
//                            public View newView(Context context, Cursor cursor, ViewGroup parent) {
//                                TextView tv = new TextView(context);
//                                return tv;
//                            }
//
//                            @Override
//                            public void bindView(View view, Context context, Cursor cursor) {
//                                TextView tv = (TextView) view;
//                                 //具体设置数据
//                                 String body = cursor.getString(cursor.getColumnIndex(SmsOpenHelper.SMSTable.BODY));
//                                 tv.setText(body);
//                            }


                            @Override
                            public int getItemViewType(int position) {
                                //接受-->如果当前账号不等于消息的创建者
                                cursor.moveToPosition(position);
                                String fromAccount = cursor.getString(cursor.getColumnIndex(SmsOpenHelper.SMSTable.FROM_ACCOUNT));
                                if (!IMService.mCurAccount.equals(fromAccount)) {
                                    return RECEIVE;
                                } else {
                                    return SEND;
                                }
                                //发送
//                                return super.getItemViewType(position);//0 1
                            }

                            @Override
                            public int getViewTypeCount() {
                                return super.getViewTypeCount() + 1;// 2种item布局类型
                            }

                            @Override
                            public View getView(int position, View convertView, ViewGroup parent) {
                                Integer viewType = getItemViewType(position);
                                ViewHolder holder = new ViewHolder();
                                switch (viewType) {
                                    case RECEIVE:
                                        if (convertView == null) {
                                            convertView = View.inflate(ChatActivity.this, R.layout.item_chat_recv, null);
                                            convertView.setTag(holder);
                                            holder.time = convertView.findViewById(R.id.time);
                                            holder.body = convertView.findViewById(R.id.content);
                                            holder.head = convertView.findViewById(R.id.head);
                                        } else {
                                            holder = (ViewHolder) convertView.getTag();
                                        }
                                        break;
                                    case SEND:
                                        if (convertView == null) {
                                            convertView = View.inflate(ChatActivity.this, R.layout.item_chat_send, null);
                                            convertView.setTag(holder);
                                            holder.time = convertView.findViewById(R.id.time);
                                            holder.body = convertView.findViewById(R.id.content);
                                            holder.head = convertView.findViewById(R.id.head);
                                        } else {
                                            holder = (ViewHolder) convertView.getTag();
                                        }
                                        break;
                                }
                                cursor.moveToPosition(position);
                                String time = cursor.getString(cursor.getColumnIndex(SmsOpenHelper.SMSTable.TIME));
                                String body = cursor.getString(cursor.getColumnIndex(SmsOpenHelper.SMSTable.BODY));
                                String formatTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(Long.parseLong(time)));
//                                holder.time.setText(formatTime);
                                holder.body.setText(body);

                                return super.getView(position, convertView, parent);
                            }

                            @Override
                            public View newView(Context context, Cursor cursor, ViewGroup parent) {
                                return null;
                            }

                            @Override
                            public void bindView(View view, Context context, Cursor cursor) {

                            }

                            class ViewHolder {
                                TextView body;
                                TextView time;
                                ImageView head;
                            }
                        };
                        mListView.setAdapter(mAdapter);
                        mListView.setSelection(mAdapter.getCount() - 1);
                    }
                });
            }
        });
    }

    private void initView() {
        mTitle = findViewById(R.id.title);
        mListView = findViewById(R.id.listView);
        mEtBody = findViewById(R.id.et_body);
        mBtnSend = findViewById(R.id.btn_send);
        mTitle.setText("与" + clickNickName + "聊天中");
    }

    private void init() {
        registerContentObserver();
        //绑定服务
        Intent service = new Intent(ChatActivity.this, IMService.class);
        bindService(service, myServiceConnection, BIND_AUTO_CREATE);
        clickAccount = getIntent().getStringExtra(ChatActivity.CLICKACCOUNT);
        clickNickName = getIntent().getStringExtra(ChatActivity.CLICKNICKNAME);
    }

    @Override
    protected void onDestroy() {
        unRegisterContentObserver();
        //解绑服务
        if (myServiceConnection != null) {
            unbindService(myServiceConnection);
        }
        super.onDestroy();
    }


    MyContentObserver myContentObserver = new MyContentObserver(new Handler());

    /**
     * 注册监听
     */
    public void registerContentObserver() {
        getContentResolver().registerContentObserver(SmsProvider.URI_SMS, true, myContentObserver);
    }

    /**
     * 反注册监听
     */
    public void unRegisterContentObserver() {
        getContentResolver().unregisterContentObserver(myContentObserver);
    }

    class MyContentObserver extends ContentObserver {

        /**
         * Creates a content observer.
         *
         * @param handler The handler to run {@link #onChange} on, or null if none.
         */
        public MyContentObserver(Handler handler) {
            super(handler);
        }

        /**
         * 接受到数据记录的改变
         */
        @Override
        public void onChange(boolean selfChange, Uri uri) {
            //设置adapter或者notifyadapter
            setAdapterOrNotify();
            super.onChange(selfChange, uri);
        }
    }

    MyServiceConnection myServiceConnection = new MyServiceConnection();

    class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            IMService.MyBinder myBinder = (IMService.MyBinder) service;
            mImService = myBinder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }
}
